package com.dingpeikeji.quickdeer.mobile.service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
import com.dingpeikeji.quickdeer.modules.rcpt.entity.TRcpt;
import com.dingpeikeji.quickdeer.modules.rcpt.entity.TUsersRcpt;
import com.dingpeikeji.quickdeer.modules.rcpt.service.TRcptService;
import com.dingpeikeji.quickdeer.modules.rcpt.service.TUsersRcptService;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ShareRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.ShareProductService;
import com.dingpeikeji.quickdeer.utils.BackResult;
import com.dingpeikeji.quickdeer.utils.OrderUtil;
import com.tencent.WXPay;
import com.tencent.protocol.unifiedorder_protocol.UnifiedorderReqDataApp;

@Service
@Transactional(readOnly = true)
public class MobileRcptService {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private TUsersRcptService tUsersRcptService;
	@Autowired
	private TOrdersService ordersService;
	@Autowired
	private TRcptService tRcptService;
	@Autowired
	private ShareProductService shareProductService;
	@Autowired
	private FrontUserService frontUserService;
	
	private static final String RSA2_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBK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NNkmF1bHYAHBgrRlPgLMCUL7eW10bs5l5B+IToQPNtIkP79PlZ62Ch+6gWcRfEncwKv4g1Q5obS1WUqOaFaVitcOoVzqSLmNPzFwxxyYR1LsLH8Rc5ry0o8zxTassfHTrb6QBrW8hVodPzzz9BNAoGADdwqlL/TYyOEXC9vkYSx/ESZDgwU9LzVv6EQ5dOM2M4v3MoPdD0REW4/vArRMPw47GABGOcRzE5uq2duqbOXsdK0oEl343vPiZGR7uwgPSGroIUfgX9iemMZsRoHoA70F20HUgIujGpIW6NFCYfAXTZCPEyLQ4VJ2odXDZlIv+ECgYEArnqEzlnWAs/S2n1Col4C32r4WIZOVXA29r08jK5cVvxugY0uLC6eKuXUOJaTU8GYJ7ASG5wHbtYcx+Vq6FECfIq7gBpkayz5oOeatoIsyYvHTh8KMComzfXHry3NmRuMBTXL1m5xK6crgQIiCFiMwwkLZ9y/Npp2K/aHjYzUo+Q=";
	
	private static final String RSA_PRIVATE = "";

	private static final String APPID = "2017071207730951";
	
	public BackResult rcptHistory(TUsersRcpt tUsersRcpt,String userid, HttpServletRequest request, 
			HttpServletResponse response,String pageNo,String pageSize) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 当前订票人
		User user = frontUserService.get(userid);
		if (user==null) {
			return BackResult.build("400", "未查询到用户信息");
		}
		TRcpt rcpt = new TRcpt();
		rcpt.setCreateBy(user);
		Page<TRcpt> page = new Page<TRcpt>(request, response);
		page.setPageNo(Integer.parseInt(pageNo));
		page.setPageSize(Integer.parseInt(pageSize));
		page = tRcptService.findPage(new Page<TRcpt>(request, response), rcpt);
		if (page.getCount()==0) {
			return BackResult.build("400", "未查询到开票记录");
		}
		List<TRcpt> list = page.getList();
		if(list!=null&&list.size()>0){
			for (TRcpt tr : list) {
				double parseDouble = tr.getTotalOutkmsfee();
				double parseDouble2 = tr.getTotalOuttimefee();
				double parseDouble3 = tr.getTotalRirverfee();
				double parseDouble4 = tr.getRcptamount();
				double total = parseDouble+parseDouble2+parseDouble3+parseDouble4;
				tr.setTotalPrice(total+"");//发票总金额
			}
		}
		map.put("rcptList", page.getList());
		map.put("totalCount", page.getCount());
		return BackResult.ok(map);
	}
	//开票信息
	public BackResult userRcptInfo(TUsersRcpt tUsersRcpt,String userid) {
		Map<String, Object> map = new HashMap<String, Object>();
		User user = frontUserService.get(userid);
		if (user==null) {
			return BackResult.build("400", "未查询到用户信息");
		}
		tUsersRcpt = tUsersRcptService.getByUserid(user.getId());
		if (tUsersRcpt==null||tUsersRcpt.getAlwaysid()==null) {
			return BackResult.build("400", "未查询到数据");
		}
		map.put("tUsersRcpt", tUsersRcpt);
		return BackResult.ok(map);
	}
	//开票信息
	public BackResult saveUserRcptInfo(TUsersRcpt tUsersRcpt,String userid) {
		Map<String, Object> map = new HashMap<String, Object>();
		User user = frontUserService.get(userid);
		if (user==null) {
			return BackResult.build("400", "未查询到用户信息");
		}
		if(StringUtils.isBlank(tUsersRcpt.getUserid())){
			tUsersRcpt.setUserid(user.getId());
		}
		TUsersRcpt usersRcpt = tUsersRcptService.getByUserid(user.getId());
		tUsersRcpt.setRcpttype("1");
		tUsersRcpt.setAlwaysid(usersRcpt.getAlwaysid());
		tUsersRcptService.save(tUsersRcpt);
		map.put("tUsersRcpt", tUsersRcpt);
		return BackResult.ok(map);
	}
	//可开票订单查看
	public BackResult rcptOrders(String userid, String pageNo,String pageSize,
			HttpServletRequest request,HttpServletResponse response) {
		TOrders orders = new TOrders();
		// 当前订票人
		User user = frontUserService.get(userid);
		if (user==null) {
			return BackResult.build("400", "未查询到用户信息");
		}
		orders.setOrderuserid(user.getId());
		orders.setOrderstatus(TOrders.STATUS_PAY);
		orders.setGenRcpt("no"); // 未开发票
		Page<TOrders> page = new Page<TOrders>(request, response);
		page.setPageNo(Integer.parseInt(pageNo));
		page.setPageSize(Integer.parseInt(pageSize));
		page = ordersService.findPage(new Page<TOrders>(request, response), orders);
		if (page.getCount()==0) {
			return BackResult.build("400", "暂未有可开发票订单");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ordersList",page.getList());
		map.put("totalCount", page.getCount());
		return BackResult.ok(map);
	}
	//开票
	public BackResult saveRcpt(TUsersRcpt tUsersRcpt,String rcptIds,String userid,String outkmsfee,
			String outtimefee,String dirverfee) {
		User user = frontUserService.get(userid);
		if (user==null) {
			return BackResult.build("400", "未查询到用户信息");
		}
		if(StringUtils.isBlank(tUsersRcpt.getUserid())){
			tUsersRcpt.setUserid(user.getId());
		}
		//获取总的超公里费
		String[] kmsArr = outkmsfee.split(",");
		double totalKmsFee = 0D;
		if (kmsArr.length>0) {
			for (String km : kmsArr) {
				totalKmsFee += Double.parseDouble(km);
			}
		}
		tUsersRcpt.setTotalOutkmsfee(totalKmsFee);
		//获取总的超时长费
		String[] timeArr = outtimefee.split(",");
		double totalTimeFee = 0D;
		if (timeArr.length>0) {
			for (String tm : timeArr) {
				totalTimeFee += Double.parseDouble(tm);
			}
		}
		tUsersRcpt.setTotalOuttimefee(totalTimeFee);
		//获取总的司机费用
		String[] driverArr = dirverfee.split(",");
		double totalDriverFee = 0D;
		if (driverArr.length>0) {
			for (String da : driverArr) {
				totalDriverFee += Double.parseDouble(da);
			}
		}
		tUsersRcpt.setTotalRirverfee(totalDriverFee);
		tUsersRcpt.setRcpttype("1");
		tUsersRcptService.save(tUsersRcpt);
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(rcptIds)) {
			TUsersRcpt ur = tUsersRcptService.getByUserid(user.getId());
			ur.setTotalOutkmsfee(totalKmsFee);
			ur.setTotalOuttimefee(totalTimeFee);
			ur.setTotalRirverfee(totalDriverFee);
			if(ur.getAlwaysid() == null) {
				return BackResult.build("400", "请先填写发票信息！");
			}
			this.tUsersRcptService.genRcpts(rcptIds,ur, user);
			return BackResult.build("200", "提交用户发票信息成功");
			
		}
		return BackResult.ok(map);
	}
	/**
	 * app支付宝
	 * @throws UnsupportedEncodingException 
	 */
	public BackResult getAliPayParams(String tradeNo, String userid) {
		User user = frontUserService.get(userid);
		if (user==null) {
			return BackResult.build("400", "非法参数");
		}
	    //tradeNo 商户订单号
	    //subject 订单标题
	    //body 对交易或商品的描述
		try {
			boolean rsa2 = (RSA2_PRIVATE.length() > 0);
			//根据订单号查询金额
			TOrders tOrders = ordersService.get(tradeNo);
			if (!tOrders.getOrderuserid().equals(userid)) {
				return BackResult.build("400", "获取订单信息失败");
			}
			if (!TOrders.STATUS_NO_PAY.equals(tOrders.getOrderstatus())) {//未支付状态才可以支付
				return BackResult.build("400", "该订单不可支付");
			}
			//AA拼车,支付的时候再次判断拼车产品剩余预订人数
			String shareid = tOrders.getShareid();
			ShareRentproduct shareRentproduct = shareProductService.getInfo(shareid);
			//剩余可预订数量
			if(shareRentproduct!=null){
			int maxCartCount = Integer.parseInt(shareRentproduct.getMinamount()) - shareRentproduct.getCurrentsell();
				if (tOrders.getPaycount() > maxCartCount) {
					return BackResult.build("400", "当前拼车最多可拼车人数:"+maxCartCount+",请重新预定");
				}
				if (shareRentproduct.getEnddate().before(new Date())) {
					return BackResult.build("400", "产品已过期,请重新预定");
				}
			}
			String price = tOrders.getDueamount();
			Map<String, String> params = OrderUtil.buildOrderParamMap(APPID, rsa2, tradeNo, tOrders.getOrdername(), tOrders.getOrdername(), price);
			String orderParam = OrderUtil.buildOrderParam(params);
			String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
			//签名
			String result = OrderUtil.getSign(orderParam, privateKey, rsa2);
			return BackResult.ok(result);
		} catch (Exception e) {
			e.printStackTrace();
			return BackResult.build("400", "系统异常");
		}
	}
	/**
	 * app微信
	 */
	public BackResult getWxPayParams(String tradeNo,String userid) {
		User user = frontUserService.get(userid);
		if (user==null) {
			return BackResult.build("400", "非法参数");
		}
		//tradeNo 商户订单号
		//subject 订单标题
		//body 对交易或商品的描述
		try {
			//根据订单号查询金额
			TOrders tOrders = ordersService.get(tradeNo);
			if (!tOrders.getOrderuserid().equals(userid)) {
				return BackResult.build("400", "获取订单信息失败");
			}
			if (!TOrders.STATUS_NO_PAY.equals(tOrders.getOrderstatus())) {//未支付状态才可以支付
				return BackResult.build("400", "该订单不可支付");
			}
			//AA拼车,支付的时候再次判断拼车产品剩余预订人数
			String shareid = tOrders.getShareid();
			ShareRentproduct shareRentproduct = shareProductService.getInfo(shareid);
			//剩余可预订数量
			if(shareRentproduct!=null){
			int maxCartCount = Integer.parseInt(shareRentproduct.getMinamount()) - shareRentproduct.getCurrentsell();
			if (tOrders.getPaycount() > maxCartCount) {
				return BackResult.build("400", "当前拼车最多可拼车人数:"+maxCartCount+",请重新预定");
			}
			if (shareRentproduct.getEnddate().before(new Date())) {
				return BackResult.build("400", "产品已过期,请重新预定");
			}
			}
			BigDecimal b1 = new BigDecimal(tOrders.getDueamount());//1.00
			BigDecimal b2 = new BigDecimal("100");
			Float money = b1.multiply(b2).floatValue();//100.0,整形,单位为分
			String outTradeNo = "";
			for(int i=0;i<32-tOrders.getOrderid().length();i++){ // 补齐32位字符串
				outTradeNo+="0";
			}
			outTradeNo += tOrders.getOrderid();//商户系统内部订单号，要求32个字符内
			UnifiedorderReqDataApp unifiedorderReqData = new UnifiedorderReqDataApp(tOrders.getOrdername()
					, outTradeNo
					, (int)money.floatValue()
					, Global.getConfig("wx.pay.ip")
					, Global.getConfig("wx.pay.notify_url")
					, "APP");//APP支付和pc支付交易类型不同
			String result = WXPay.requestUnifiedorderAPPService(unifiedorderReqData);
			logger.debug("微信预支付返回信息={}", result);
			Document doc = DocumentHelper.parseText(result);
			Element root = doc.getRootElement();			
			Element prepay_id = root.element("prepay_id");
			Element nonce_str = root.element("nonce_str");
			Element sign_wx = root.element("sign");
			if (prepay_id==null && nonce_str!=null && sign_wx!=null) {
				return BackResult.build("400", "系统异常");
			}
			String prepayId = prepay_id.getTextTrim();//得到预支付id
			String param = UnifiedorderReqDataApp.getPaySign(prepayId);
			String[] arr = param.split("#");
			Map<String, String> params = new HashMap<String, String>();
			//赋值
			params.put("appid", unifiedorderReqData.getAppid());
			params.put("partnerid", unifiedorderReqData.getMch_id());//商户号
			params.put("prepayId", prepayId);//微信返回的支付交易会话ID
			params.put("packageValue", "Sign=WXPay");//暂填写固定值Sign=WXPay
			params.put("nonceStr", arr[1]);//随机字符串
			params.put("timeStamp", (System.currentTimeMillis() / 1000)+"");//时间戳
			params.put("sign", arr[0]);//签名
			return BackResult.ok(params);
		} catch (Exception e) {
			e.printStackTrace();
			return BackResult.build("400", "系统异常");
		}
	}
	

}
























